<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>商场消防云平台 - 消防设备管理系统</title>
    <script src="js/jquery-3.7.1.js"></script>
    <style>
        body { margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f5f5f5; }
        .header { background-color: #409EFF; color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center; }
        .nav { background-color: #333; overflow: hidden; display: flex; }
        .nav a { color: white; padding: 14px 16px; text-decoration: none; font-size: 17px; }
        .nav a:hover { background-color: #ddd; color: black; }
        .nav a.active { background-color: #f44336; color: white; }
        .container { padding: 20px; max-width: 1200px; margin: 0 auto; }
        .equipment-table { width: 100%; border-collapse: collapse; margin-top: 20px; background-color: white; box-shadow: 0 0 5px rgba(0,0,0,0.1); }
        .equipment-table th, .equipment-table td { border: 1px solid #ddd; padding: 12px 8px; text-align: left; }
        .equipment-table th { background-color: #f2f2f2; font-weight: bold; }
        .operation-btn { padding: 6px 12px; border: none; border-radius: 4px; cursor: pointer; margin-right: 5px; }
        .edit-btn { background-color: #409EFF; color: white; }
        .delete-btn { background-color: #f44336; color: white; }
        .check-btn { background-color: #67c23a; color: white; }
        .add-btn { padding: 8px 20px; background-color: #67c23a; color: white; border: none; border-radius: 4px; cursor: pointer; margin-bottom: 10px; font-size: 14px; }
        .modal-mask { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: none; justify-content: center; align-items: center; z-index: 999; }
        .modal { width: 500px; background: #fff; border-radius: 8px; box-shadow: 0 0 20px rgba(0,0,0,0.2); overflow: hidden; }
        .modal-header { padding: 15px; background-color: #f8f9fa; border-bottom: 1px solid #ddd; font-size: 18px; font-weight: bold; }
        .modal-body { padding: 20px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: bold; }
        .form-group input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .modal-footer { padding: 15px; background-color: #f8f9fa; border-top: 1px solid #ddd; text-align: right; }
        .modal-footer button { padding: 8px 20px; margin-left: 10px; border: none; border-radius: 4px; cursor: pointer; }
        .btn-save { background-color: #409EFF; color: white; }
        .btn-cancel { background-color: #ccc; color: #333; }
        .status-normal { color: green; font-weight: bold; }
        .status-warning { color: orange; font-weight: bold; }
        .status-danger { color: red; font-weight: bold; }
    </style>
</head>
<body>
<div class="header">
    <h1>商场消防云平台</h1>
    <div><a href="LogoutServlet">退出登录</a></div>
</div>

<div class="nav">
    <a href="main.jsp">首页</a>
    <a href="fire_alarm_list.jsp">火灾报警系统</a>
    <a href="equipment_management.jsp" class="active">消防设备管理系统</a>
    <a href="inspection_system.jsp" >设备巡检系统</a>
    <a href="video_monitoring.jsp">视频监控系统</a>
    <a href="emergency_plan.jsp">应急预案管理</a>
    <%
        String role = (String) session.getAttribute("role");
        if ("管理人员".equals(role)) {
    %>
    <a href="duty_staff.jsp">检查人员管理</a>
    <a href="system.jsp">系统设置</a>

    <% } %>
    <a href="change_password.jsp">修改密码</a>
</div>

<div class="container">
    <h2>消防设备管理系统</h2>

    <div class="form-group">
        <label for="searchKey">搜索设备编号、位置或类型：</label>
        <input type="text" id="searchKey" placeholder="输入关键词搜索">
        <button class="add-btn" style="margin-left: 10px" onclick="searchEquipments()">搜索</button>
    </div>

    <table class="equipment-table" id="equipmentTable">
        <thead>
        <tr>
            <th>ID</th>
            <th>设备编号</th>
            <th>类型</th>
            <th>型号</th>
            <th>位置</th>
            <th>状态</th>
            <th>最后检查</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过 AJAX 加载 -->
        </tbody>
    </table>

    <button class="add-btn" onclick="showAddModal()">添加设备</button>

    <!-- 新增/编辑弹窗 -->
    <div class="modal-mask" id="modalMask">
        <div class="modal">
            <div class="modal-header" id="modalTitle">添加消防设备</div>
            <div class="modal-body">
                <input type="hidden" id="equipmentId" name="id">
                <div class="form-group">
                    <label for="equipNo">设备编号：</label>
                    <input type="text" id="equipNo" name="equipNo" placeholder="如：XF-001" required>
                </div>
                <div class="form-group">
                    <label for="type">类型：</label>
                    <input type="text" id="type" name="type" placeholder="如：灭火器、消防栓等">
                </div>
                <div class="form-group">
                    <label for="model">型号：</label>
                    <input type="text" id="model" name="model" placeholder="如：ABC4、MFZ/ABC6等">
                </div>
                <div class="form-group">
                    <label for="location">位置：</label>
                    <input type="text" id="location" name="location" placeholder="如：1楼大厅东侧">
                </div>
                <div class="form-group">
                    <label for="status">状态：</label>
                    <select id="status" name="status">
                        <option value="正常">正常</option>
                        <option value="待检修">待检修</option>
                        <option value="故障">故障</option>
                        <option value="已过期">已过期</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="lastCheck">最后检查日期：</label>
                    <input type="date" id="lastCheck" name="lastCheck">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-cancel" onclick="closeModal()">取消</button>
                <button class="btn-save" onclick="saveEquipment()">保存</button>
            </div>
        </div>
    </div>
</div>

<script>
    // 页面加载时加载设备数据
    $(document).ready(function() {
        loadEquipments();
    });

    // 加载设备列表
    function loadEquipments(searchKey) {
        searchKey = searchKey || "";
        $.ajax({
            url: "FireEquipmentServlet",
            method: "GET",
            data: {
                action: "list",
                searchKey: searchKey
            },
            dataType: "json",
            success: function(data) {
                var tbody = $("#equipmentTable tbody");
                tbody.empty();

                if (data.error) {
                    tbody.append("<tr><td colspan='8' style='text-align: center; color: red;'>" + data.error + "</td></tr>");
                    return;
                }

                if (data.length === 0) {
                    tbody.append("<tr><td colspan='8' style='text-align: center; color: #999;'>暂无数据</td></tr>");
                    return;
                }

                // 渲染表格数据
                data.forEach(function(equipment) {
                    // 设置状态样式
                    let statusClass = "";
                    switch(equipment.status) {
                        case "正常":
                            statusClass = "status-normal";
                            break;
                        case "待检修":
                            statusClass = "status-warning";
                            break;
                        case "故障":
                        case "已过期":
                            statusClass = "status-danger";
                            break;
                    }

                    tbody.append(
                        "<tr>" +
                        "<td>" + equipment.id + "</td>" +
                        "<td>" + equipment.equipNo + "</td>" +
                        "<td>" + equipment.type + "</td>" +
                        "<td>" + (equipment.model || "未知") + "</td>" +
                        "<td>" + equipment.location + "</td>" +
                        "<td><span class='" + statusClass + "'>" + equipment.status + "</span></td>" +
                        "<td>" + (equipment.lastCheck || "未检查") + "</td>" +
                        "<td>" +
                        "<button class='operation-btn edit-btn' onclick=\"editEquipment(" + equipment.id + ")\">编辑</button>" +
                        "<button class='operation-btn delete-btn' onclick=\"deleteEquipment(" + equipment.id + ")\">删除</button>" +
                        "<button class='operation-btn check-btn' onclick=\"submitToInspection(" + equipment.id + ")\">提交巡检</button>" +
                        "</td>" +
                        "</tr>"
                    );
                });
            },
            error: function() {
                $("#equipmentTable tbody").html("<tr><td colspan='8' style='color: red; text-align: center;'>数据加载失败，请稍后重试</td></tr>");
            }
        });
    }

    // 搜索设备
    function searchEquipments() {
        var searchKey = $("#searchKey").val().trim();
        loadEquipments(searchKey);
    }

    // 显示添加设备弹窗
    function showAddModal() {
        $("#modalTitle").text("添加消防设备");
        $("#equipmentId").val("");
        $("#equipNo").val("");
        $("#type").val("");
        $("#model").val("");
        $("#location").val("");
        $("#status").val("正常");
        $("#lastCheck").val("");

        $("#modalMask").css("display", "flex");
    }

    // 关闭弹窗
    function closeModal() {
        $("#modalMask").css("display", "none");
    }

    // 编辑设备
    function editEquipment(id) {
        $.ajax({
            url: "FireEquipmentServlet",
            method: "GET",
            data: {
                action: "get",
                id: id
            },
            dataType: "json",
            success: function(data) {
                if (data.error) {
                    alert(data.error);
                    return;
                }

                // 填充表单数据
                $("#modalTitle").text("编辑消防设备");
                $("#equipmentId").val(data.id);
                $("#equipNo").val(data.equipNo || "");
                $("#type").val(data.type || "");
                $("#model").val(data.model || "");
                $("#location").val(data.location || "");
                $("#status").val(data.status || "正常");
                $("#lastCheck").val(data.lastCheck || "");

                $("#modalMask").css("display", "flex");
            },
            error: function() {
                alert("获取数据失败，请重试");
            }
        });
    }

    // 删除设备
    function deleteEquipment(id) {
        if (!confirm("确定要删除这条设备记录吗？")) {
            return;
        }

        $.ajax({
            url: "FireEquipmentServlet",
            method: "GET",
            data: {
                action: "delete",
                id: id
            },
            dataType: "json",
            success: function(res) {
                if (res.success) {
                    alert("删除成功");
                    loadEquipments();
                } else {
                    alert("删除失败：" + (res.error || "未知错误"));
                }
            },
            error: function() {
                alert("网络异常，请重试");
            }
        });
    }

    // 保存设备
    function saveEquipment() {
        var id = $("#equipmentId").val();
        var equipNo = $("#equipNo").val().trim();
        var type = $("#type").val().trim();
        var model = $("#model").val().trim();
        var location = $("#location").val().trim();
        var status = $("#status").val();
        var lastCheck = $("#lastCheck").val();

        // 表单验证
        if (!equipNo || !type || !location) {
            alert("请填写必填信息");
            return;
        }

        var url = "FireEquipmentServlet";
        var data = {
            action: id ? "update" : "add",
            id: id,
            equipNo: equipNo,
            type: type,
            model: model,
            location: location,
            status: status,
            lastCheck: lastCheck
        };

        $.ajax({
            url: url,
            method: "POST",
            data: data,
            dataType: "json",
            success: function(res) {
                if (res.success) {
                    alert(id ? "更新成功" : "添加成功");
                    closeModal();
                    loadEquipments();
                } else {
                    alert("操作失败：" + (res.error || "未知错误"));
                }
            },
            error: function() {
                alert("网络异常，请重试");
            }
        });
    }
    function submitToInspection(equipmentId) {
        // 关键：确保获取的是当前行设备的真实数据
        var currentRow = $(event.target).closest("tr"); // 替换原来的 firstRow，精准获取当前行
        if (!currentRow.length) {
            alert("无设备数据可提交");
            return;
        }

        var equipmentId = currentRow.find("td:eq(0)").text(); // 设备ID
        var equipNo = currentRow.find("td:eq(1)").text();    // 设备编号
        var status = currentRow.find("td:eq(5) span").text();// 设备状态

        $.ajax({
            url: "http://localhost:8080/demo_war_exploded/InspectionSystemServlet",
            method: "POST",
            data: {
                action: "create",
                equipmentId: equipmentId,
                equipmentNo: equipNo,
                equipmentStatus: status
            },
            dataType: "json",
            success: function(res) {
                if (res.success) {
                    alert("提交成功！已创建巡检任务");
                } else {
                    alert("提交失败：" + res.error);
                }
            },
            error: function() {
                alert("网络异常，提交失败");
            }
        });
    }
</script>
</body>
</html>